<?php

namespace addons\Flow\api\modules\v1\controllers;


use addons\Flow\common\models\Metadata;
use addons\Flow\common\models\Status;
use Yii;
use yii\data\ActiveDataProvider;
use common\enums\StatusEnum;
use common\helpers\ArrayHelper;
use common\helpers\ResultHelper;
use api\controllers\OnAuthController;
use addons\Flow\common\models\Works;
use yii\db\Expression;

/**
 * @property \yii\db\ActiveRecord|\yii\base\Model $modelClass;
 * @author 古月 <21931118@qq.com>
 */
class WorksController extends OnAuthController
{
    public $modelClass = Works::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['index', 'update', 'view'];

    /**
     * 首页
     *
     * @return ActiveDataProvider
     */
    public function actionIndex()
    {
        if (Yii::$app->request->get('state') == 1) {
            $where = new Expression("FIND_IN_SET(:supplier, audit_ids)", [":supplier" => Yii::$app->user->identity->member_id??0]);
            return new ActiveDataProvider([
                'query' => $this->modelClass::find()
                    ->where(['status' => StatusEnum::ENABLED])
                    ->andWhere($where)
                    ->with(['member'])
                    ->orderBy('id desc')
                    ->asArray(),
                'pagination' => [
                    'pageSize' => $this->pageSize,
                    'validatePage' => false,// 超出分页不返回data
                ],
            ]);
        } elseif (Yii::$app->request->get('state') == 0) {
            return new ActiveDataProvider([
                'query' => $this->modelClass::find()
                    ->where(['status' => StatusEnum::ENABLED])
                    ->andWhere(['audit_id' => Yii::$app->user->identity->member_id??0])
                    ->with(['member'])
                    ->orderBy('id desc')
                    ->asArray(),
                'pagination' => [
                    'pageSize' => $this->pageSize,
                    'validatePage' => false,// 超出分页不返回data
                ],
            ]);
        }
    }


    public function actionUpdate($id)
    {
        $works = $this->findModel($id);
        $model = $works->model::findOne($works->work_id);
        $model->attributes = Yii::$app->request->post();
        if (!$model->save()) {
            return ResultHelper::json(422, $this->getError($model));
        }
        return $model;
    }

    public function actionView($id)
    {
        $works = $this->findModel($id);
        $model = $works->model::findOne($works->work_id);
        $radioList = [];
        foreach ($model->getNextStatuses() as $key => $nextStatus) {
            $radioList[$key] = $nextStatus['status']->getLabel();
        }
        asort($radioList, SORT_STRING);

        foreach ($model->log as $key => $log) {
            $log->name = Yii::$app->flowService->member->getName($log->id);
            if ($key == 0) $log->suggest = '提交申请';
            $log->approve = \addons\Flow\common\enums\WorkflowEnum::getValue(explode('/', $log->action)[1]);
        }

        $model->log = array_reverse($model->log);
        return ['model' => $model, 'works' => $works, 'radioList' => ArrayHelper::arrayToArrays($radioList)];
    }

    public function actionReset()//提交重审，重置流程为apply状态
    {
        $id = Yii::$app->request->get('id', null);
        $works = $this->findModel($id);
        $model = $works->model::findOne($works->work_id);
        $audit = Status::find()->andWhere(['workflow_id' => $works->workflow_id, 'id' => 'apply', 'merchant_id' => Yii::$app->user->identity->merchant_id])->one();
        //确定审核人
        $metadata = Metadata::find()->andWhere(['workflow_id' => $works->workflow_id, 'status_id' => 'apply', 'merchant_id' => Yii::$app->user->identity->merchant_id])->asArray()->all();
        //某状态设置了元数据启用单独审核
        $flag = 0;
        if ($metadata) {
            $member_ids = '';
            foreach ($metadata as $meta) {
                if ($meta['key'] == 'audit_id') $audit_id = $meta['value'];
                if ($meta['key'] == 'member_id') $member_ids = $meta['value'];
                if ($meta['key'] == 'end_mark' && $meta['value'] == 'true') $flag = 1;
            }
            //在单独审核的用户名单里情况
            if ($flag == 1 && in_array($works->member_id, explode(',', $member_ids))) $audit->audit_id = 0;
            if ($flag == 0 && in_array($works->member_id, explode(',', $member_ids))) $audit->audit_id = $audit_id;
            //不在单独审核用户名单里的情况
            if ($flag == 1 && !in_array($works->member_id, explode(',', $member_ids))) {
                if ($audit->type == 0 && $audit->audit_id) $audit->audit_id = $audit->audit_id;
                else if ($audit->type == 1 && $audit->role_id) $audit->audit_id = Yii::$app->merchantsService->member->getLeaderRoleId($works->member_id, $audit->role_id);
            }
            if ($flag == 0 && !in_array($works->member_id, explode(',', $member_ids))) {
                if ($audit->type == 0 && $audit->audit_id) $works->audit_id = $audit->audit_id;
                else if ($audit->type == 1 && $audit->role_id) $audit->audit_id = Yii::$app->merchantsService->member->getLeaderRoleId($works->member_id, $audit->role_id);
            }
        }
        //某状态未设置元数据的情况
        if (!$metadata) {
            if ($audit->type == 0 && $audit->audit_id) $audit->audit_id = $audit->audit_id;
            else if ($audit->type == 1 && $audit->role_id) $audit->audit_id = Yii::$app->merchantsService->member->getLeaderRoleId($works->member_id, $audit->role_id);
        }
        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $arr = $model->log ? $model->log : [];
            $log = ["id" => Yii::$app->user->identity->member_id, "time" => time(), "action" => $works->workflow_id . '/apply', "suggest" => Yii::$app->request->post('suggest') . ' 流程重置为申请状态。'];
            array_push($arr, $log);
            $log = json_encode($arr);

            $model::updateAll(['log' => $log, 'state' => 'apply', 'status' => $works->workflow_id . '/apply'], ['id' => $works->work_id]);
            Works::updateAll(['audit_id' => $audit->audit_id, 'audit_ids' => Null, 'state' => 'apply'], ['id' => $id]);
            //推送短信或消息
            if ($model->remind == 0 && $audit->audit_id > 0 && Yii::$app->merchantsService->member->getMember($audit->audit_id)->mobile) Yii::$app->services->sms->send(Yii::$app->merchantsService->member->getMember($audit->audit_id)->mobile, '申请', 'audit');
            if ($model->remind == 1 && $audit->audit_id > 0) Yii::$app->services->backendNotify->createMessage($works->content, Yii::$app->user->id, $audit->audit_id);
            $transaction->commit();

        } catch (\Exception $e) {
            $transaction->rollBack();
            return 'error';
        }
        return $works;
    }

    public function actionState()
    {
        return ArrayHelper::arrayToArrays(\addons\Flow\common\enums\WorkflowEnum::getMap());
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, ['delete'])) {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}